package com.cloud.demo2020.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.demo2020.common.ResultBean;
import com.cloud.demo2020.entity.SysToken;
import com.cloud.demo2020.entity.SysUser;
import com.cloud.demo2020.entity.SysUserDto;
import com.cloud.demo2020.mapper.SysTokenMapper;
import com.cloud.demo2020.mapper.SysUserMapper;
import com.cloud.demo2020.service.CodeService;
import com.cloud.demo2020.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

@RestController
public class UserController {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysTokenMapper sysTokenMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private CodeService codeService;

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public ResultBean login(@RequestBody SysUser user) {
        SysUser dbUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("email", user.getEmail()));
        if (dbUser == null) {
            return new ResultBean(false, "该用户不存在!");
        }
        boolean flag = dbUser.getPassword().equals(user.getPassword());
        if (!flag) {
            return new ResultBean(false, "密码不匹配,请重新输入!");
        }
        SysToken token = this.sysTokenMapper
                .selectOne(new QueryWrapper<SysToken>().eq("email", dbUser.getEmail()));
        // 全局只允许录入一次
        if (token == null) {
            token.setEmail(dbUser.getEmail());
            token.setToken(UUID.randomUUID().toString());
            token.setUpdatetime(new Date());
            this.sysTokenMapper.insert(token);
        }

        return new ResultBean(token);
    }

    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public ResultBean register(@RequestBody SysUserDto user) {
        return this.userService.register(user);
    }

    @RequestMapping(value = "/user/isRegister/{email}")
    public ResultBean isRegister(@PathVariable("email") String email) {
        int cnt = sysUserMapper.selectCount(new QueryWrapper<SysUser>()
                .eq("email", email));
        return new ResultBean(cnt > 0);
    }

    @RequestMapping(value = "/user/info/{token}")
    public ResultBean info(@PathVariable("token") String token) {
        SysToken item = this.sysTokenMapper.selectOne(
                new QueryWrapper<SysToken>().eq("token", token));
        if (item == null) {
            return new ResultBean(false, "非法输入,请校验token");
        }
        return new ResultBean(item);
    }

    @RequestMapping(value = "/user/fallback/{email}")
    public ResultBean fallback(@PathVariable("email") String email) {
        return this.codeService.create(email);
    }

}
